#!/bin/bash

echo "=== 启动SmartInput后端服务 ==="

cd backend

# 默认profile
DEFAULT_PROFILE="dev"

# 检查命令行参数
if [ $# -eq 0 ]; then
    PROFILE=$DEFAULT_PROFILE
    echo "使用默认profile: $PROFILE"
else
    PROFILE=$1
    echo "使用指定profile: $PROFILE"
fi

# 自动创建必要的目录
echo "创建必要的目录..."
if [ "$PROFILE" = "dev" ]; then
    mkdir -p logs
    mkdir -p ~/audio_files
    echo "✅ 创建开发环境目录: logs/, ~/audio_files/"
elif [ "$PROFILE" = "prod" ]; then
    sudo mkdir -p /var/log/smartinput
    sudo mkdir -p /var/smartinput/audio_files
    sudo chown $USER:$USER /var/log/smartinput
    sudo chown $USER:$USER /var/smartinput/audio_files
    echo "✅ 创建生产环境目录: /var/log/smartinput/, /var/smartinput/audio_files/"
fi

echo "1. 编译Kotlin代码..."
mvn kotlin:compile

if [ $? -eq 0 ]; then
    echo "✅ Kotlin编译成功"
    echo "2. 启动Spring Boot应用..."
    
    # 检查是否存在jar文件
    if [ -f "target/smartinput-backend-*.jar" ]; then
        echo "使用jar文件启动..."
        JAR_FILE=$(ls target/smartinput-backend-*.jar | head -1)
        java -jar -Dspring.profiles.active=$PROFILE $JAR_FILE
    else
        echo "使用Maven启动..."
        mvn spring-boot:run -Dspring-boot.run.profiles=$PROFILE
    fi
else
    echo "❌ Kotlin编译失败"
    exit 1
fi 